package xj.toolkit.netty.util.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinitionVisitor;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringValueResolver;

/**
 * 忽略掉不能解析的占位符，以info级别的log输出
 */
public class LazyBeanDefinitionVisitor extends BeanDefinitionVisitor {
	private static final Logger logger = LoggerFactory.getLogger(LazyBeanDefinitionVisitor.class);
	private boolean ignoreInvalidKeys;

	/**
	 * Create a new BeanDefinitionVisitor, applying the specified value resolver to
	 * all bean metadata values.
	 *
	 * @param valueResolver
	 *            the StringValueResolver to apply
	 */
	public LazyBeanDefinitionVisitor(StringValueResolver valueResolver, boolean ignoreInvalidKeys) {
		super(valueResolver);
		this.ignoreInvalidKeys = ignoreInvalidKeys;
	}

	@Override
	protected void visitPropertyValues(MutablePropertyValues pvs) {
		PropertyValue[] pvArray = pvs.getPropertyValues();
		for (PropertyValue pv : pvArray) {
			try {
				Object newVal = resolveValue(pv.getValue());
				if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) {
					pvs.add(pv.getName(), newVal);
				}
			} catch (IllegalArgumentException ex) {
				if (!this.ignoreInvalidKeys) {
					throw ex;
				}
				logger.info(ex.getMessage());
				pvs.removePropertyValue(pv);
			}
		}
	}
}
